//
//  MYComposeView.swift
//  MYWeibo
//
//  Created by Magic Yu on 16/4/22.
//  Copyright © 2016年 Magic Yu. All rights reserved.
//

import UIKit

class MYComposeView: UIView {
    
    var target: UIViewController?
    
    //外界调用的方法 将当前的视图对象添加到视图上 设置target值
    func show(target: UIViewController) {
    
        self.target = target
        //使用target的view 添加自己
        target.view.addSubview(self)
    }

    override init(frame: CGRect) {
        let rect = UIScreen.mainScreen().bounds
        super.init(frame: rect )
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //点击屏幕退出视图
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for (index,button) in buttonArray.reverse().enumerate() {
            animationWith(button, index: index)
        }
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //执行动画 依次获取每个按钮 给按钮添加动画  需要增加一个属性数组 记录所有的按钮
        for (index,button) in buttonArray.enumerate() {
            animationWith(button, index: index, isUp: true)
        }
    }
    
    private func animationWith(button: MYComposeButton, index: Int, isUp: Bool = false) {
    
        UIView.animateWithDuration(0.8, delay: Double(index) * 0.03, usingSpringWithDamping: 0.7, initialSpringVelocity: 5, options: [], animations: { () -> Void in
            //修改按钮的中心点
            button.center = CGPoint(x: button.center.x, y: button.center.y + (isUp ? -350 : 350))
            }) { (_) -> Void in
                if !isUp {
                    //按钮动画完成之后 视图退出
                self.removeFromSuperview()
                }
        }
    }
    
    
    
    //MARK: 设置UI界面
    private func setupUI() {
        
       //backgroundColor = randomColor()
        //添加子视图
        addSubview(imgView)
        addSubview(sloganView)
        //设置约束
        imgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
        
        sloganView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.top.equalTo(self.snp_top).offset(100)
        }
        
        //添加按钮
        addChildBtn()
        
    }
    
    //按钮的点击事件
    @objc private func btnDidClick(btn: MYComposeButton) {
        
        var scale: CGFloat = 0
        for button in buttonArray {
            //被点击的按钮放大
            if button == btn {
                scale = 2.0
                //其他按钮缩小
            }else {
            scale = 0.1
            }
            
            //执行动画效果
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                button.alpha = 0
                button.transform = CGAffineTransformMakeScale(scale, scale)
                }, completion: { (_) -> Void in
                    //将当前视图移除父视图
                    //self.removeFromSuperview()
                    print("OK")
            })
        }
        
        //跳转页面
        //获取按钮对应的模型
        guard let className = btn.composeItem?.target else {
        print("className 为空")
            return
        }
        
        //fatal error: unexpectedly found nil while unwrapping an Optional value
        //在配置plist文件时 给target的值前面加上命名空间
        
        //根据字符串获取对应的类型
        let classType = NSClassFromString(className) as! UIViewController.Type
        let vc = classType.init()
        let nav = UINavigationController(rootViewController: vc)
        //跳转
        target?.presentViewController(nav, animated: true, completion: { () -> Void in
            self.removeFromSuperview()
        })
        
    }
    
    
    
    private func addChildBtn() {
    
        let count = composeInfo.count
        let width: CGFloat = 80
        let height: CGFloat = 110
        let margin: CGFloat = (ScreenWidth - 3 * width) / 4
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        for i in 0..<count {
            
            let item = composeInfo[i]
            let btn = MYComposeButton ()
            btn.composeItem = item
            
            
            btn.titleLabel?.textAlignment = .Center
            btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)

            
            addSubview(btn)
            
            //设置按钮frame
            let row = i / 3
            let col = i % 3
            let offsetX = (width + margin) * CGFloat(col) + margin
            let offsetY = (height + margin) * CGFloat(row) + ScreenHeight
            btn.frame = CGRectOffset(rect, offsetX, offsetY)
            
            buttonArray.append(btn)
            
            //给按钮添加点击事件
            btn.addTarget(self, action: "btnDidClick:", forControlEvents: .TouchUpInside)
        }
    
    }
    
    //MARK: 懒加载子视图
    //背景图片
    private lazy var imgView: UIImageView = UIImageView(image: UIImage.snapShotScreen().applyLightEffect())
    private lazy var sloganView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    //声明保存按钮的数组
    private lazy var buttonArray: [MYComposeButton] = [MYComposeButton]()
    
    private lazy var composeInfo: [MYComposeItem] = {
        //从文件中读取数组
        let path = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: path) as! [[String: String]]
        //遍历数组 字典转模型
        var tempArray = [MYComposeItem]()
        for item in array {
        let composeItem = MYComposeItem(dict: item)
            tempArray.append(composeItem)
        }
        return tempArray
    }()

}
